<template>

  <div class="search-box">
    <div class="flex">
      <div>
        <el-icon>
          <Search />
        </el-icon><span>筛选搜索</span>
      </div>
      <div>
        <el-button @click="resetForm">重置</el-button>
        <el-button @click="submitFn" type="primary">查询搜索</el-button>
      </div>

    </div>
    <div style="padding-top: 20px">
      <el-form @submit.prevent="submitFn" ref="searchFormRef" :model="listParams">
        <el-form-item label="活动名称" prop="keyword" label-width="120px">
          <el-input v-model="listParams.keyword" style="width: 200px" placeholder="活动名称"></el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
  <!-- 添加 -->
  <div class="add-box">
    <i class="el-icon-edit"></i>
    <el-button @click="router.push('/sms/flashSession')">秒杀时间段列表</el-button>
    <el-button @click="addUser">添加活动</el-button>
  </div>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="编号" prop="id"> </el-table-column>
    <el-table-column label="活动标题" prop="title"> </el-table-column>
    <el-table-column label="活动状态" prop="nickName"> </el-table-column>
    <el-table-column prop="startDate" label="开始时间">
      <template #default="scope">
        {{ fomatDate(scope.row.startDate) }}
      </template>
    </el-table-column>
    <el-table-column prop="endDate" label="结束时间">
      <template #default="scope">
        {{ fomatDate(scope.row.endDate) }}
      </template>
    </el-table-column>
    <el-table-column label="上线下线">
      <!-- 通过插槽得到的scope.row是每一列里面的 数据对象 -->
      <template #default="scope">
        <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="changeHandle(scope.row)" />
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">

        <el-button link type="primary" @click="router.push(`/sms/selectSession?flashPromotionId=${scope.row.id}`)">设置商品</el-button>
        <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
        <el-button type="text" @click="sureFn(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <ElConfigProvider :locale="zhCn">
    <el-pagination v-model:currentPage="listParams.pageNum" v-model:page-size="listParams.pageSize"
      :page-sizes="[10, 20, 50, 100]" background layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="pageSizeChagne" @current-change="currentChange" />
  </ElConfigProvider>

  <addEdit :show="showEditUser" @hide="hideDialog" @refresh="getList" :data="editId" />

  <AllocRole :show="showAllocRole" @hide="hideAlloc" :data="allocRoleId" />
</template>

<script lang="ts" setup>
import addEdit from "./components/addEdit.vue";
import { reactive, ref, toRefs } from "vue";
import { user } from "@/api";
import { fomatDate } from "@/utils";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { ElConfigProvider } from "element-plus";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import AllocRole from "./components/AllocRole.vue";
import { useRouter } from "vue-router";

const router = useRouter();
interface IState {
  tableData: IUserModel[];
  listParams: IUserListParams;
  total: number;
}

const state = reactive<IState>({
  tableData: [],
  listParams: {
    keyword: "",
    pageNum: 1,
    pageSize: 10,
  },
  total: 0,
});


// 数据
const getList = () => {
  user.getMiaoshaApi(state.listParams).then((res) => {
    if (res.code === 200) {
      state.tableData = res.data.list;
      state.tableData.forEach((item, index) => {
        state.tableData[index].nickName = "活动未开始"

      });

      state.total = res.data.total;
    }
  });
};
getList();

// 开始就要调用一次
const submitFn = () => {
  state.listParams.pageNum = 1;
  getList();
};
// 分页
const pageSizeChagne = (val: number) => {
  getList();
};
const currentChange = (val: number) => {
  // val是新的页码
  //   获取新的数据进行渲染
  console.log(val);

  getList();
};

// 分配角色
const showAllocRole = ref(false);
const allocRoleId = ref(0)

// 分配角色隐藏
const hideAlloc = () => {
  showAllocRole.value = false;
  allocRoleId.value = 0
};

const editId = ref();
// 传值
const editHandle = (id: number) => {
  const bj = tableData.value.findIndex(item => item.id === id)
  editId.value = tableData.value[bj];
  showEditUser.value = true;
};
// 用户状态的管理
const changeHandle = (row: IUserModel) => {
  console.log(row.id, row.status);

  user
    .userMiaoshaApi({ id: row.id, status: row.status })
    .then((res) => {
      ElMessage({
        message: res.message,
        type: res.code === 200 ? "success" : "error",
      });
    })
    .catch((err) => {
      // 如果请求失败，会走catch
      // 把 switch 恢复成之前的状态 -
      // 方式1
      row.status = row.status === 1 ? 0 : 1;
      //   方式二
      //   let target = state.tableData.find((item) => item.id === row.id);
      //   target && (target.status = row.status === 1 ? 0 : 1)
    });
};
// 重置
const searchFormRef = ref<FormInstance>();
const resetForm = () => {
  searchFormRef.value?.resetFields();
};
// addUser添加
const showEditUser = ref(false);
const addUser = () => {
  showEditUser.value = true;
};
// addUser取消
const hideDialog = () => {
  showEditUser.value = false;
  // 还要把 editId 归 0
  editId.value = 0;
};


const sureFn = (id: number) => {
  ElMessageBox.confirm("是否要删除该活动？", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    user.flashdeleteApi(id).then((res) => {
      if (res.code === 200) {
        ElMessage.success("删除活动成功");
        getList();
      }
    });
  });

};

let { tableData, listParams, total } = toRefs(state);
</script>

<style lang="less" scoped>
.search-box {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;

  .flex {
    display: flex;
    justify-content: space-between;
  }
}

.add-box {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
  margin: 20px;
  border-radius: 10px;
  box-shadow: 0 0 4px 2px #ccc;
}
</style>
